using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Matrix.Configuration.DTOs;
using Matrix.Configuration.Contracts;
using Matrix.Configuration.Application.Services;

namespace Matrix.Configuration.Application
{
    /// <summary>
    /// 配置管理应用服务 - 协调器模式
    /// 负责协调查询服务、命令服务和缓存服务，提供统一的配置管理接口
    /// </summary>
    public class ConfigurationAppService : ApplicationService, IConfigurationAppService
    {
        private readonly Contracts.IConfigurationQueryService _queryService;
        private readonly Contracts.IConfigurationCommandService _commandService;
        private readonly Contracts.IConfigurationCacheService _cacheService;
        private readonly ILogger<ConfigurationAppService> _logger;

        public ConfigurationAppService(
            Contracts.IConfigurationQueryService queryService,
            Contracts.IConfigurationCommandService commandService,
            Contracts.IConfigurationCacheService cacheService,
            ILogger<ConfigurationAppService> logger)
        {
            _queryService = queryService;
            _commandService = commandService;
            _cacheService = cacheService;
            _logger = logger;
        }

        // === 查询操作委托给查询服务 ===

        /// <summary>
        /// 获取配置项列表
        /// </summary>
        public async Task<PagedResultDto<ConfigurationItemDto>> GetListAsync(GetConfigurationItemListInput input)
        {
            _logger.LogDebug("协调器处理获取配置列表请求");
            return await _queryService.GetListAsync(input);
        }

        /// <summary>
        /// 根据ID获取配置项
        /// </summary>
        public async Task<ConfigurationItemDto> GetAsync(Guid id)
        {
            _logger.LogDebug("协调器处理根据ID获取配置项请求: {Id}", id);
            return await _queryService.GetAsync(id);
        }

        /// <summary>
        /// 通过键名获取配置值
        /// </summary>
        public async Task<ConfigurationItemDto> GetByKeyAsync(GetConfigurationItemInput input)
        {
            _logger.LogDebug("协调器处理通过键名获取配置值请求: {Key} - {Namespace}", input.Key, input.Namespace);
            return await _queryService.GetByKeyAsync(input);
        }

        /// <summary>
        /// 通过命名空间获取配置列表
        /// </summary>
        public async Task<ListResultDto<ConfigurationItemDto>> GetByNamespaceAsync(string @namespace)
        {
            _logger.LogDebug("协调器处理通过命名空间获取配置列表请求: {Namespace}", @namespace);
            return await _queryService.GetByNamespaceAsync(@namespace);
        }

        /// <summary>
        /// 检查配置是否存在
        /// </summary>
        public async Task<bool> ExistsAsync(GetConfigurationItemInput input)
        {
            _logger.LogDebug("协调器处理检查配置是否存在请求: {Key} - {Namespace}", input.Key, input.Namespace);
            return await _queryService.ExistsAsync(input);
        }

        /// <summary>
        /// 获取类型化配置值
        /// </summary>
        public async Task<T> GetTypedAsync<T>(GetConfigurationItemInput input)
        {
            _logger.LogDebug("协调器处理获取类型化配置值请求: {Key} - {Type}", input.Key, typeof(T).Name);
            return await _queryService.GetTypedAsync<T>(input);
        }

        /// <summary>
        /// 批量获取配置
        /// </summary>
        public async Task<Dictionary<string, ConfigurationItemDto>> GetBatchAsync(List<GetConfigurationItemInput> inputs)
        {
            _logger.LogDebug("协调器处理批量获取配置请求，数量: {Count}", inputs?.Count ?? 0);
            return await _queryService.GetBatchAsync(inputs);
        }

        // === 写操作委托给命令服务 ===

        /// <summary>
        /// 创建配置项
        /// </summary>
        public async Task<ConfigurationItemDto> CreateAsync(CreateConfigurationItemDto input)
        {
            _logger.LogInformation("协调器处理创建配置项请求: {Key} - {Namespace}", input.Key, input.Namespace);

            try
            {
                var result = await _commandService.CreateAsync(input);

                // 清除相关缓存
                await _cacheService.RemoveAsync(input.Key, input.Namespace);
                // // await _cacheService.ClearNamespaceCacheAsync(input.Namespace); // 暂时注释，待接口实现完成 // 暂时注释，待接口实现完成

                _logger.LogInformation("协调器完成创建配置项: {Key} - {Namespace}", input.Key, input.Namespace);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "协调器创建配置项失败: {Key} - {Namespace}", input.Key, input.Namespace);
                throw;
            }
        }

        /// <summary>
        /// 更新配置项
        /// </summary>
        public async Task<ConfigurationItemDto> UpdateAsync(Guid id, UpdateConfigurationItemDto input)
        {
            _logger.LogInformation("协调器处理更新配置项请求: {Id}", id);

            try
            {
                var result = await _commandService.UpdateAsync(id, input);

                // 清除相关缓存
                await _cacheService.RemoveAsync(result.Key, result.Namespace);
                // await _cacheService.ClearNamespaceCacheAsync(result.Namespace); // 暂时注释，待接口实现完成

                _logger.LogInformation("协调器完成更新配置项: {Id} - {Key}", id, result.Key);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "协调器更新配置项失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 删除配置项
        /// </summary>
        public async Task DeleteAsync(Guid id)
        {
            _logger.LogInformation("协调器处理删除配置项请求: {Id}", id);

            try
            {
                // 先获取配置项信息以便清理缓存
                var configItem = await _queryService.GetAsync(id);

                await _commandService.DeleteAsync(id);

                // 清除相关缓存
                await _cacheService.RemoveAsync(configItem.Key, configItem.Namespace);
                // await _cacheService.ClearNamespaceCacheAsync(configItem.Namespace); // 暂时注释，待接口实现完成

                _logger.LogInformation("协调器完成删除配置项: {Id} - {Key}", id, configItem.Key);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "协调器删除配置项失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 通过键名删除配置
        /// </summary>
        public async Task DeleteByKeyAsync(GetConfigurationItemInput input)
        {
            _logger.LogInformation("协调器处理通过键名删除配置请求: {Key} - {Namespace}", input.Key, input.Namespace);

            try
            {
                await _commandService.DeleteByKeyAsync(input);

                // 清除相关缓存
                await _cacheService.RemoveAsync(input.Key, input.Namespace);
                // // await _cacheService.ClearNamespaceCacheAsync(input.Namespace); // 暂时注释，待接口实现完成 // 暂时注释，待接口实现完成

                _logger.LogInformation("协调器完成通过键名删除配置: {Key} - {Namespace}", input.Key, input.Namespace);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "协调器通过键名删除配置失败: {Key} - {Namespace}", input.Key, input.Namespace);
                throw;
            }
        }

        /// <summary>
        /// 设置类型化配置值
        /// </summary>
        public async Task SetTypedAsync<T>(GetConfigurationItemInput input, T value)
        {
            _logger.LogInformation("协调器处理设置类型化配置值请求: {Key} - {Type} - {Namespace}",
                input.Key, typeof(T).Name, input.Namespace);

            try
            {
                await _commandService.SetTypedAsync(input, value);

                // 清除相关缓存
                await _cacheService.RemoveAsync(input.Key, input.Namespace);
                // // await _cacheService.ClearNamespaceCacheAsync(input.Namespace); // 暂时注释，待接口实现完成 // 暂时注释，待接口实现完成

                _logger.LogInformation("协调器完成设置类型化配置值: {Key} - {Type}", input.Key, typeof(T).Name);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "协调器设置类型化配置值失败: {Key} - {Type}", input.Key, typeof(T).Name);
                throw;
            }
        }

        /// <summary>
        /// 批量设置配置
        /// </summary>
        public async Task<ListResultDto<ConfigurationItemDto>> SetBatchAsync(List<BatchConfigurationItemDto> configurations)
        {
            _logger.LogInformation("协调器处理批量设置配置请求，数量: {Count}", configurations?.Count ?? 0);

            try
            {
                var result = await _commandService.SetBatchAsync(configurations);

                // 清除相关缓存
                var namespaces = configurations.Select(c => c.Namespace).Distinct().ToList();
                foreach (var ns in namespaces)
                {
                    // await _cacheService.ClearNamespaceCacheAsync(ns); // 暂时注释，待接口实现完成
                }

                foreach (var config in configurations)
                {
                    await _cacheService.RemoveAsync(config.Key, config.Namespace);
                }

                _logger.LogInformation("协调器完成批量设置配置，成功数量: {Count}", result.Items.Count);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "协调器批量设置配置失败");
                throw;
            }
        }

        // === 协调器特有功能 ===

        /// <summary>
        /// 清除指定配置的缓存
        /// </summary>
        public async Task ClearCacheAsync(string key, string @namespace = "")
        {
            _logger.LogInformation("协调器处理清除缓存请求: {Key} - {Namespace}", key, @namespace);
            await _cacheService.RemoveAsync(key, @namespace);
        }

        /// <summary>
        /// 清除命名空间的所有缓存
        /// </summary>
        public async Task ClearNamespaceCacheAsync(string @namespace)
        {
            _logger.LogInformation("协调器处理清除命名空间缓存请求: {Namespace}", @namespace);
            // await _cacheService.ClearNamespaceCacheAsync(@namespace); // 暂时注释，待接口实现完成
        }

        /// <summary>
        /// 清除所有配置缓存
        /// </summary>
        public async Task ClearAllAsync()
        {
            _logger.LogInformation("协调器处理清除所有缓存请求");
            await _cacheService.ClearAllAsync();
        }

        /// <summary>
        /// 预热缓存
        /// </summary>
        public async Task WarmupCacheAsync()
        {
            _logger.LogInformation("协调器处理缓存预热请求");

            try
            {
                // 获取所有配置项用于预热
                var allConfigsInput = new GetConfigurationItemListInput { MaxResultCount = 1000 };
                var allConfigs = await _queryService.GetListAsync(allConfigsInput);

                // await _cacheService.WarmupCacheAsync(allConfigs.Items.ToList()); // 暂时注释，待接口实现完成

                _logger.LogInformation("协调器完成缓存预热，处理配置项数量: {Count}", allConfigs.Items.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "协调器缓存预热失败");
                throw;
            }
        }

        /// <summary>
        /// 获取缓存统计信息
        /// </summary>
        public async Task<DTOs.CacheStatisticsDto> GetCacheStatisticsAsync()
        {
            _logger.LogDebug("协调器处理获取缓存统计信息请求");
            // return await _cacheService.GetCacheStatisticsAsync(); // 暂时注释，待接口实现完成
            return new DTOs.CacheStatisticsDto(); // 返回空对象
        }
    }
}